/******************************************************************************

    Copyright (C) 2006 Alessio Stalla (alessiostalla@gmail.com)

    This file is part of PrettyProlog.

    PrettyProlog is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    PrettyProlog is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with PrettyProlog; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

    See the file COPYING for further details.

 *****************************************************************************/

package prettyprolog.engine.syspreds;

import java.net.MalformedURLException;
import java.util.List;

import prettyprolog.datatypes.CharString;
import prettyprolog.datatypes.Substitution;
import prettyprolog.datatypes.Term;
import prettyprolog.engine.Engine;

/**
 * Implements the system predicate consult/1, that allows to load a theory from an URL resource.
 */
public class Consult extends SystemPredicate {

	private static final Consult inst = new Consult();

	private Consult() {
		super(1);
	}

	/** Returns the only instance of this system predicate. */
	public static Consult getInstance() {
		return inst;
	}

	/**
	 * @throws SyspredException
	 *             if the argument is not a string or does not name an existing resource.
	 */
	public SyspredEffect doCall(Engine en, Substitution subst, List<Term> args) throws SyspredException {
		Term t = args.get(0);
		if(t instanceof CharString) {
			try {
				en.loadTheory(((CharString) t).getString());
			} catch(MalformedURLException e) {
				throw new SyspredException(t + " is not a valid URL.", e);	
			} catch(Exception e) {
				throw new SyspredException("Couldn't consult " + t + ": " + e, e);
			}
		} else {
			throw new SyspredException(args.get(0) + " is not a string.");
		}
		return new SyspredEffect(false, subst);
	}

	public boolean isBacktrackable() {
		return false;
	}

	public String toString() {
		return super.toString() + " consult";
	}
}